package controllers

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	_ "fmt"
	"gitchina/smartguard-api/models"
	"os"
	"time"

	"github.com/astaxie/beego"
)

var salt = []byte("**#%")

type ApiController struct {
	beego.Controller
}

// @router /sync/meta [post]
func (api *ApiController) SyncMeta() {
	fmt.Println(string(api.Ctx.Input.RequestBody))
}

// @router /sync/time [get]
func (api *ApiController) Now() {
	api.Ctx.WriteString(time.Now().Format("2006-01-02 15:04:05"))
}

// @router /sync/profile [get]
func (api *ApiController) GetProfile() {
	id := api.GetString("id", "")
	profile := models.Profile{
		Time: time.Now().Format("2006-01-02 15:04:05"),
	}
	if school := models.GetConnectedSchool(id); school != nil {
		profile.Host = school.LocalIP
	}
	api.Data["json"] = profile
	api.ServeJSON()
}

// @router /image/credential [get]
func (api *ApiController) GetUploadCredential() {
	var oss models.OSS
	api.Ctx.WriteString(oss.Credential())
}

// @router /school [get]
func (api *ApiController) ListSchool() {
	if id := api.GetString("id", ""); id == "" {

	} else {

	}
}

// @router /school/connect [post]
func (api *ApiController) AcceptSchool() {
	var rq models.School
	if err := json.Unmarshal(api.Ctx.Input.RequestBody, &rq); err == nil {
		rq.Connect()
	}
}

// @router /school/connected [get]
func (api *ApiController) ListConnected() {
	api.Data["json"] = models.GetAllConnectedSchools()
	api.ServeJSON()
}

// @router /upload [post]
func (api *ApiController) Upload() {
	t := api.GetString("type", "")
	n := api.GetString("name", "")
	c := api.GetString("crc", "")

	if t != "" && n != "" && c != "" {
		p := api.Ctx.Input.RequestBody
		if crc := fmt.Sprintf("%x", md5.Sum(append(p, salt...))); crc == c {
			fmt.Println("crc correct!")
			if f, err := os.Create(fmt.Sprintf("%s/%s/%s_%s.db",
				beego.AppConfig.String("uploadDir"), t, n, time.Now().Format("20060102150405"))); err == nil {
				f.Write(p)
			} else {
				fmt.Println(err.Error())
			}
		} else {
			fmt.Println("crc not correct")
		}
	}
}
